import request from "./request_nest.js"
import store from "@/store/index.js"
// #ifdef H5
import { clockin } from "@/api/mission.js"
import dd from "gdt-jsapi"
import { CoolWPDistance } from "@/utils/base"
import { authReady } from "@/utils/JSAPI_init"
// #endif


export function voice2Text(media_id: string): Promise<string> {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: "语音转化中"
		})
		
		request({
			url: "/common/recordToText",
			method: "POST",
			params: { media_id }
		}).then((res: any) => {
			uni.hideLoading()
			resolve(res.data)
		}).catch(() => {
			uni.hideLoading()
		})
	})
	
}


export function text2Voice(text: string): Promise<any> {
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: "加载中"
		})
		
		request({
			url: "/common/text2Voice",
			method: "POST",
			params: { text }
		}).then((res: any) => {
			uni.hideLoading()
			resolve(res)
		}).catch((err) => {
			uni.hideLoading()
			reject(err)
		})
	})
}

export function downloadFile(params: any): Promise<any> {
	return new Promise((resolve, reject) => {
		request({
			url: "/common/downloadFile",
			method: "POST",
			params: params
		}).then((res: any) => {
			resolve(res)
		}).catch((err) => {
			reject(err)
		})
	})
}

/**
 * 获取应用Ticket
 */
export function getTicket(): Promise<any> {
	return new Promise((resolve, reject) => {
		request({
			url: "/common/getTicket",
			method: "GET"
		}).then((res: any) => {
			console.log("res",res)
			resolve(res)
		}).catch((err: any) => {
			console.log("err",err)
			reject(err)
		})
	})
}

/**
 * 开启全局定位
 * @return 
 */ 
export function globalLocale() {
	authReady(() => {
		console.log("加载完成"), 
		dd.startGeolocation({
			"targetAccuracy": 200,
			"useCache": false,
			"callBackInterval": 6000,
			"sceneId": "global",
			// "withReGeocode": true,
			"onSuccess": (res) => {
				// uni.showToast({
				// 	icon: "none",
				// 	title: "全局定位"
				// })
				const obj = Object.assign(res, { username: store.getters.userInfo.username }) 
				request({
					url: "/common/report",
					method: "POST",
					params: obj
				}).then((res: any) => {
				}).catch((err) => {
				})
				
				store.state.WFLocaleSchools.map((mission, i) => {
					if (!mission.isclock && CoolWPDistance(Number(mission.school.longitude), Number(mission.school.latitude), Number(res.longitude), Number(res.latitude)) < 5000) {
						clockin(mission.task.id)
							.then(() => {
								uni.showToast({
									icon: "none",
									title: "已为您自动打卡【" + mission.school.name + "】"
								})
								store.state.WFLocaleSchools[i].isclock = true
							})
					}
				})
			}
		})
	})
}

// /**
//  * 判断用户受否有某权限
//  */
// export function hasPermission(permission: string) {
// 	const permissions = store.state.userInfo.permissions
// 	return 
// }